package com.javabasic.algorithm.sword_of_offer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2022/1/10 11:58 下午
 */
public class 剑指_Offer_32_I_从上到下打印二叉树 {

    /**
     * 二叉树的层序遍历 BFS
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        List<Integer> nums = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode currentNode;
        while (!queue.isEmpty()) {
            currentNode = queue.poll();
            nums.add(currentNode.val);
            if (currentNode.left != null) {
                queue.offer(currentNode.left);
            }
            if (currentNode.right != null) {
                queue.offer(currentNode.right);
            }
        }
        int[] result = new int[nums.size()];
        int index = 0;
        for (Integer num : nums) {
            result[index++] = num;
        }
        return result;
    }
}
